<template>
  <view class="tab-bar">
    <view class="tab-item" v-for="(item, index) in tabList" :key="index" @click="handleTabClick(item)"
      :class="{ active: currentPath === item.path }">
      <image :src="currentPath === item.path ? item.selectedIcon : item.icon" class="tab-icon"></image>
      <text class="tab-text">{{ item.text }}</text>
    </view>
  </view>
</template>

<script setup>
  import { ref, onMounted } from 'vue'

  const currentPath = ref('')
  const tabList = [
    {
      text: '首页',
      path: '/pages/index/index',
      icon: '/static/index/tab_2.png',
      selectedIcon: '/static/index/tab_1.png'
    },
    {
      text: '我的',
      path: '/pages/my/index',
      icon: '/static/index/tab_4.png',
      selectedIcon: '/static/index/tab_3.png'
    }
  ]

  // 预加载页面
  const preloadPages = () => {
    tabList.forEach(item => {
      uni.preloadPage({
        url: item.path
      })
    })
  }

  // 处理标签点击
  const handleTabClick = (item) => {
    if (currentPath.value === item.path) return

    // 使用 reLaunch 实现无感跳转
    uni.reLaunch({
      url: item.path,
      success: () => {
        currentPath.value = item.path
      }
    })
  }

  onMounted(() => {
    // 获取当前页面路径
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    currentPath.value = '/' + currentPage.route

    // 预加载所有页面
    preloadPages()
  })
</script>

<style lang="scss" scoped>
  .tab-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 140rpx;
    display: flex;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    background: linear-gradient(to bottom, #D4EFF6, #fff);
    border-top-right-radius: 100rpx;
    border-top-left-radius: 100rpx;
    z-index: 990;

    .tab-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .tab-icon {
        width: 32rpx;
        height: 32rpx;
        margin-bottom: 4rpx;
      }

      .tab-text {
        margin-top: 4rpx;
        font-size: 23rpx;
        color: #666;
      }

      &.active {
        .tab-text {
          color: #2196F3;
        }
      }
    }
  }
</style>